package com.mustafaiev.tair.cts.factory;

import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.mustafaiev.tair.cts.dao.BasketDAO;
import com.mustafaiev.tair.cts.dao.BasketsBatchDAO;
import com.mustafaiev.tair.cts.dao.PayerDAO;
import com.mustafaiev.tair.cts.dao.PurchaseDAO;
import com.mustafaiev.tair.cts.exeptions.ContextCreationException;
import com.mustafaiev.tair.cts.facade.BasketFacade;
import com.mustafaiev.tair.cts.facade.BasketsBatchFacade;
import com.mustafaiev.tair.cts.facade.IBasketFacade;
import com.mustafaiev.tair.cts.facade.IBasketsBatchFacade;
import com.mustafaiev.tair.cts.facade.ICostTrackingSystemFacade;
import com.mustafaiev.tair.cts.facade.IPayerFacade;
import com.mustafaiev.tair.cts.facade.IPurchaseFacade;
import com.mustafaiev.tair.cts.facade.PayerFacade;
import com.mustafaiev.tair.cts.facade.PurchaseFacade;
import com.mustafaiev.tair.cts.tapestry.services.DozerMapper;

public class CostTrackingSystemFacadeFactory implements
		ICostTrackingSystemFacadeFactory {

	private final Map<Class<?>, Object> facades = new HashMap<Class<?>, Object>();
	private final DozerMapper mapper;
	private static final Logger LOGGER = Logger
			.getLogger(CostTrackingSystemFacadeFactory.class);

	public CostTrackingSystemFacadeFactory() {
		this.mapper = new DozerMapper();
		initFacadeFactory();
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T extends ICostTrackingSystemFacade> T getFacade(
			final Class<T> facade) {
		return (T) this.facades.get(facade);
	}

	private void initFacadeFactory() {
		createPayerFacade();
		createBasketFacade();
		createPurchaseFacade();
		createBasketsBatchFacade();
	}

	private void createPayerFacade() {
		IPayerFacade facade = null;
		try {
			facade = new PayerFacade(new PayerDAO(), this.mapper.getMapper());
		} catch (final ContextCreationException e) {
			LOGGER.error(e.getLocalizedMessage());
		}
		this.facades.put(IPayerFacade.class, facade);
	}

	private void createBasketFacade() {
		IBasketFacade facade = null;
		try {
			facade = new BasketFacade(new BasketDAO(), this.mapper.getMapper());
		} catch (final ContextCreationException e) {
			LOGGER.error(e.getLocalizedMessage());
		}
		this.facades.put(IBasketFacade.class, facade);
	}

	private void createPurchaseFacade() {
		IPurchaseFacade facade = null;
		try {
			facade = new PurchaseFacade(new PurchaseDAO(),
					this.mapper.getMapper());
		} catch (final ContextCreationException e) {
			LOGGER.error(e.getLocalizedMessage());
		}
		this.facades.put(IPurchaseFacade.class, facade);
	}

	private void createBasketsBatchFacade() {
		IBasketsBatchFacade facade = null;
		try {
			facade = new BasketsBatchFacade(new BasketsBatchDAO(),
					this.mapper.getMapper());
		} catch (final ContextCreationException e) {
			LOGGER.error(e.getLocalizedMessage());
		}
		this.facades.put(IBasketsBatchFacade.class, facade);
	}

}
